import Axios from "axios";
import KeepPromise from "./keepPromise"
import {_qs, urlParamStringify} from "./urlParamStringify"
import {loadingEnd, loadingStart} from '@/utils/modules/loading'
import {Message} from 'element-ui'

function makeStringifyUrl(shortUrl, param) {
  return config.baseURL +
  (!config.baseURL.endsWith("/") && !shortUrl.startsWith("/") ? "/" : "") +
  shortUrl + shortUrl.indexOf("?") > 0 ? "&" : "?" + urlParamStringify(param)
}

let config = {
  baseURL: process.env.VUE_APP_BASE_API || process.env.baseURL || process.env.apiUrl || "",
  timeout: 5 * 1000,
  //withCredentials: true, //请求带cookies
  headers: {
    'X-Requested-With': 'XMLHttpRequest' //标识为xdr请求
  },
  adapter: KeepPromise({keepTime: 2000}),//缓存请求
};

const _axios = Axios.create(config);


/**
 * 请求拦截
 */
_axios.interceptors.request.use(async requestConfig => {
    loadingStart();
    return requestConfig;
  }, error => {
    loadingEnd();
    return Promise.reject(error)
  }
)

/**
 * 返回拦截
 */
_axios.interceptors.response.use(responseData => {
    loadingEnd();
    const {data: apiResult} = responseData;
    return apiResult;
  }, error => {
    loadingEnd();
    if (error.response) {
      const resStatus = error.response.status
      if (resStatus === 400) {
        Message.error('请求服务器参数错误(400)!')
      } else if (resStatus === 503) {
        Message.error('服务器不可到达(503),请联系管理员！')
      } else if (resStatus === 500) {
        Message.error('服务器发生异常(500),请联系管理员！')
      } else if (resStatus === 404) {
        Message.error('请求对象未找到(404)!')
      }else{
        Message.error('其他错误('+resStatus+')!')
      }
    } else {
      //服务不可到达或未正确返回
      Message.error('网络请求服务不可到达或未正确返回错误('+error+')!')

    }
    return Promise.reject(error)
  }
)
export {_axios, _qs, urlParamStringify, makeStringifyUrl}
export default _axios

